package com.ncucoder.soms.util;

import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * jwtToken工具类
 *
 * @author <a href="https://www.ncucoder.com">hsowan</a>
 * @date 2019-07-10
 */
public class JwtTokenUtils {

    private static Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);

    private static String secret;
    private static String issuer;
    /**
     * 过期时间, 单位秒
     */
    private static long expiration;

    public static final String REQUEST_TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    public static final String RESPONSE_TOKEN_HEADER = "token";

    /**
     * 添加角色的key
     */
    private static final String ROLE_CLAIM = "role";

    static {
        secret = (String) PropertyUtils.properties.get("jwt.secret");
        issuer = (String) PropertyUtils.properties.get("jwt.issuer");
        expiration = new Long((String) PropertyUtils.properties.get("jwt.expiration"));

    }

    /**
     * 创建token
     *
     * @param username
     * @return
     */
    public static String createToken(String username, String role) {
        Map<String, Object> claims = new HashMap<>(16);
        claims.put(ROLE_CLAIM, role);

        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, secret)
                .setClaims(claims)
                .setIssuer(issuer)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .compact();
    }

    /**
     * 从token中获取用户名
     *
     * @param token
     * @return
     */
    public static String getUsername(String token){
        return getTokenBody(token).getSubject();
    }

    /**
     *
     * @param token
     * @return
     */
    private static Claims getTokenBody(String token){
        return Jwts.parser()
                .setSigningKey(secret)
                .requireIssuer(issuer)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取用户角色
     *
     * @param token
     * @return
     */
    public static String getRole(String token){
        return (String) getTokenBody(token).get(ROLE_CLAIM);
    }

    /**
     * 判断token是否有效
     *
     * @param token
     * @return jwtToken
     */
    public static String verify(String token) {
        if (token == null || !token.startsWith(TOKEN_PREFIX)) {
            return null;
        }

        token = token.replace(TOKEN_PREFIX, "");

        try {
            getTokenBody(token);
        } catch (SignatureException | IncorrectClaimException | ExpiredJwtException e) {
            logger.warn(e.getMessage());
            return null;
        }

        return token;
    }


}


